package com.lwc.service.impl;

import com.alibaba.excel.EasyExcel;
import com.lwc.bean.EnterpriseData;
import com.lwc.bean.puchare.Purchase;
import com.lwc.bean.puchare.PurchaseDetail;
import com.lwc.common.crud.BaseServiceImpl;
import com.lwc.common.exceotion.BusinessexCeption;
import com.lwc.mapper.puchase.ContractMapper;
import com.lwc.mapper.puchase.PurchaseDetailMapper;
import com.lwc.mapper.puchase.PurchaseMapper;
import com.lwc.service.PurchaseService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class PurchaseServiceImpl extends BaseServiceImpl<Purchase, PurchaseMapper> implements PurchaseService {
    String currentMaxCode;//当前最大编码  CG2024001

    @Autowired
     PurchaseDetailMapper purchaseDetailMapper;
     @Autowired
    ContractMapper contractMapper;

     @Autowired
HttpServletRequest request;

     @Transactional
    @Override
    public int save(Purchase entity) {
         entity.setCode(generateCode());
        //增加采购单
      int rs=  baseMapper.save(entity);
        if (rs==0)
        throw new BusinessexCeption("保存采购单失败");
      int rs1= purchaseDetailMapper.bathsave(entity.getId(),entity.getPurchaseDetailList());
if (rs1==0){
    throw  new BusinessexCeption("保存采购单明细失败");
}

int rs2=contractMapper.bathsave(entity.getId(),1,entity.getContractList());
if (rs2==0){
    throw  new BusinessexCeption("合同保存失败");
}
return 1;
    }


    //自动生成编码
 String  generateCode(){
String year=getYear();
//判断一下该属性是否为空
     if (null==currentMaxCode){
         //如果不存在  查询当年最大编码
         if (null==currentMaxCode){
             currentMaxCode="cg"+year+"001";
         }else { //如果存在 新编码序号+1
             getNextCode();
         }
     }else { //如果存在 新编码序号+1
         getNextCode();
     }
return currentMaxCode;
     }

     //获取下一个编码
void getNextCode(){
    //CG2024001
    String fix=currentMaxCode.substring(0,6);//前面没用的数字
    String code=currentMaxCode.substring(6);//序号
    int code1=Integer.parseInt(code);
    code1++;
    currentMaxCode=fix+ String.format("%03d", code1);
}


    String getYear(){
   int year=LocalDate.now().getYear();
    return Integer.toString(year);
     }


    @Override
    public String expose(Map map) {
            List<Purchase>list= baseMapper.export(map);
//获取服务器根目录
            String root=request.getServletContext().getRealPath("/")+"/.excel";
            //创建文件
        File file=new File(root);
        if (!file.exists())
//如果不存在 就创建文件
                file.mkdirs();
                String newFileName=file.getAbsolutePath()+"采购单报表"+".xlsx";
            EasyExcel.write(newFileName, Purchase.class)
                    .sheet("模板")
                    .doWrite(() -> {
                        return list;
                    });
        return "/excel/采购单报表.xlsx";
    }

    @Override
    public int delete(int id) {
         return baseMapper.delete(id);
    }

    @Override
    public int batchDelete(Integer[] ids) {
        return baseMapper.batchDelete(ids);
    }

    @Override
    public Purchase get(int id) {
return  baseMapper.get(id);
    }


@Transactional
    @Override
    public int update(Purchase entity) {
        //更新采购单
    int rs= baseMapper.update(entity);
    if (rs==0){
        throw  new BusinessexCeption("更新失败");
    }{
        //更新成功
            //先删除采购明细以前的明细
            purchaseDetailMapper.deleteById(entity.getId());
           //生成明细
        if (null!=entity.getPurchaseDetailList()&&entity.getPurchaseDetailList().size()>0){
            rs=purchaseDetailMapper.bathsave(entity.getId(),entity.getPurchaseDetailList());
            if (rs==0){
                throw new BusinessexCeption("更新采购明细失败");
            }
        }
//先删除合同明细
contractMapper.deleteById(entity.getId(),1);
//更新合同
        if (null!=entity.getContractList()&&entity.getContractList().size()>0){
            rs=contractMapper.bathsave(1,entity.getId(),entity.getContractList());
            if (rs==0){
                throw  new BusinessexCeption("更新合同失败");
            }
        }





        }
        return 1;
    }

}
